package com.github.aloxc.plugin.restplus.method.action;

import com.github.aloxc.plugin.restplus.annotations.SpringRequestMethodAnnotation;
import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.common.PsiMethodHelper;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.intellij.codeInsight.daemon.LineMarkerInfo;
import com.intellij.codeInsight.daemon.LineMarkerProvider;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.asJava.LightClassUtilsKt;
import org.jetbrains.kotlin.psi.KtNamedFunction;

import java.util.List;

/**
 * 在文件内容左边的竖栏上显示运行按钮
 */
public class RunLineMarkerProvider implements LineMarkerProvider {

    private static Function<PsiMethod, String> RUN_TIPS = new Function<PsiMethod, String>() {
        @Override
        public String fun(PsiMethod psiMethod) {
            return I18Bundle.getMessage("com.github.aloxc.plugin.restplus.EditorPopupMenu.run.text");
        }
    };

    @Nullable
    @Override
    public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) {
        LineMarkerInfo lineMarkerInfo = null;
        PsiMethod method = null;
        if (psiElement instanceof PsiMethod) {
            method = (PsiMethod) psiElement;
        } else if (psiElement instanceof KtNamedFunction) {
            KtNamedFunction fun = (KtNamedFunction) psiElement;
            List<PsiMethod> psiMethods = LightClassUtilsKt.toLightMethods(psiElement);
            method = psiMethods.get(0);
        } else {
            return lineMarkerInfo;
        }
        try {
            String servicePath = PsiMethodHelper.create(method).buildServiceUriPath();
//            boolean hasAnnotation = method.hasAnnotation(SpringRequestMethodAnnotation.GET_MAPPING.getQualifiedName());
//            if (hasAnnotation) {
            if (servicePath != null && servicePath.length() > 0) {
                lineMarkerInfo = new LineMarkerInfo(method, method.getNameIdentifier().getTextRange(), Consts.Icons.RUN,
                        RUN_TIPS,
                        new RunLineMarkerHandler(),
                        GutterIconRenderer.Alignment.LEFT);
            }
        } catch (Exception exe) {
            //可能该类还未初始化完成
        }
        return lineMarkerInfo;
    }
}
